import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Search, Star, Download, X } from 'lucide-react';

interface SubAgentTemplate {
  id: string;
  name: string;
  description: string;
  prompt: string;
  tools?: string[];
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
  category: string;
  tags: string[];
  rating: number;
  downloads: number;
}

interface SubAgentTemplatesProps {
  onApply: (template: SubAgentTemplate) => void;
  onClose: () => void;
}

const TEMPLATES: SubAgentTemplate[] = [
  {
    id: 'code-reviewer',
    name: 'Code Reviewer',
    description: 'Reviews code for quality, security, and best practices',
    prompt: 'You are an expert code reviewer. Analyze code for quality, security vulnerabilities, performance issues, and adherence to best practices. Provide constructive feedback with specific suggestions for improvement.',
    tools: ['Read', 'Grep', 'Glob'],
    model: 'sonnet',
    category: 'development',
    tags: ['code-review', 'quality', 'security'],
    rating: 4.8,
    downloads: 1250,
  },
  {
    id: 'test-writer',
    name: 'Test Writer',
    description: 'Generates comprehensive unit and integration tests',
    prompt: 'You are a testing expert. Write comprehensive, well-structured tests that cover edge cases, error handling, and happy paths. Follow testing best practices and use appropriate testing frameworks.',
    tools: ['Read', 'Write', 'Bash', 'Grep'],
    model: 'haiku',
    category: 'testing',
    tags: ['testing', 'unit-tests', 'tdd'],
    rating: 4.6,
    downloads: 980,
  },
  {
    id: 'api-designer',
    name: 'API Designer',
    description: 'Designs RESTful and GraphQL APIs',
    prompt: 'You are an API design expert. Create well-structured, RESTful or GraphQL APIs following industry standards. Consider versioning, authentication, rate limiting, and documentation.',
    tools: ['Read', 'Write', 'Grep'],
    model: 'sonnet',
    category: 'development',
    tags: ['api', 'rest', 'graphql'],
    rating: 4.7,
    downloads: 850,
  },
  {
    id: 'documentation-writer',
    name: 'Documentation Writer',
    description: 'Creates clear and comprehensive documentation',
    prompt: 'You are a technical documentation expert. Write clear, comprehensive documentation that is easy to understand. Include examples, diagrams, and best practices. Follow documentation standards.',
    tools: ['Read', 'Write', 'Grep', 'Glob'],
    model: 'sonnet',
    category: 'documentation',
    tags: ['docs', 'technical-writing', 'readme'],
    rating: 4.9,
    downloads: 1100,
  },
  {
    id: 'security-auditor',
    name: 'Security Auditor',
    description: 'Performs security audits and vulnerability assessments',
    prompt: 'You are a security expert. Perform thorough security audits, identify vulnerabilities, and provide remediation recommendations. Focus on OWASP Top 10, authentication, authorization, and data protection.',
    tools: ['Read', 'Grep', 'Glob', 'Bash'],
    model: 'opus',
    category: 'security',
    tags: ['security', 'audit', 'vulnerabilities'],
    rating: 4.8,
    downloads: 720,
  },
  {
    id: 'performance-optimizer',
    name: 'Performance Optimizer',
    description: 'Analyzes and optimizes code performance',
    prompt: 'You are a performance optimization expert. Analyze code for performance bottlenecks, memory leaks, and inefficiencies. Provide specific optimization recommendations with benchmarks.',
    tools: ['Read', 'Bash', 'Grep', 'Glob'],
    model: 'sonnet',
    category: 'development',
    tags: ['performance', 'optimization', 'profiling'],
    rating: 4.7,
    downloads: 890,
  },
  {
    id: 'refactoring-specialist',
    name: 'Refactoring Specialist',
    description: 'Refactors code for better maintainability',
    prompt: 'You are a refactoring expert. Improve code structure, readability, and maintainability while preserving functionality. Apply design patterns, SOLID principles, and clean code practices.',
    tools: ['Read', 'Write', 'Grep', 'Glob'],
    model: 'sonnet',
    category: 'development',
    tags: ['refactoring', 'clean-code', 'design-patterns'],
    rating: 4.6,
    downloads: 760,
  },
  {
    id: 'database-specialist',
    name: 'Database Specialist',
    description: 'Designs and optimizes database schemas',
    prompt: 'You are a database expert. Design efficient database schemas, write optimized queries, and provide indexing strategies. Consider normalization, performance, and scalability.',
    tools: ['Read', 'Write', 'Bash', 'Grep'],
    model: 'sonnet',
    category: 'database',
    tags: ['database', 'sql', 'optimization'],
    rating: 4.8,
    downloads: 680,
  },
  {
    id: 'devops-engineer',
    name: 'DevOps Engineer',
    description: 'Manages CI/CD pipelines and infrastructure',
    prompt: 'You are a DevOps expert. Design and implement CI/CD pipelines, infrastructure as code, and deployment strategies. Focus on automation, monitoring, and reliability.',
    tools: ['Read', 'Write', 'Bash', 'Grep'],
    model: 'sonnet',
    category: 'devops',
    tags: ['devops', 'ci-cd', 'infrastructure'],
    rating: 4.7,
    downloads: 820,
  },
  {
    id: 'ui-ux-reviewer',
    name: 'UI/UX Reviewer',
    description: 'Reviews user interfaces and user experience',
    prompt: 'You are a UI/UX expert. Review interfaces for usability, accessibility, and design consistency. Provide recommendations following WCAG guidelines and modern design principles.',
    tools: ['Read', 'Grep'],
    model: 'sonnet',
    category: 'design',
    tags: ['ui', 'ux', 'accessibility'],
    rating: 4.5,
    downloads: 540,
  },
];

const CATEGORIES = [
  { value: 'all', label: 'All Templates' },
  { value: 'development', label: 'Development' },
  { value: 'testing', label: 'Testing' },
  { value: 'security', label: 'Security' },
  { value: 'documentation', label: 'Documentation' },
  { value: 'database', label: 'Database' },
  { value: 'devops', label: 'DevOps' },
  { value: 'design', label: 'Design' },
];

export function SubAgentTemplates({ onApply, onClose }: SubAgentTemplatesProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [selectedTemplate, setSelectedTemplate] = useState<SubAgentTemplate | null>(null);

  const filteredTemplates = TEMPLATES.filter((template) => {
    const matchesSearch = template.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      template.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      template.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()));
    
    const matchesCategory = selectedCategory === 'all' || template.category === selectedCategory;

    return matchesSearch && matchesCategory;
  });

  const handleApply = (template: SubAgentTemplate) => {
    onApply(template);
    onClose();
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b px-6 py-4 flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">Sub-Agent Templates</h2>
          <p className="text-sm text-muted-foreground mt-1">
            Choose from {TEMPLATES.length} pre-built templates
          </p>
        </div>
        <Button variant="ghost" size="icon" onClick={onClose}>
          <X className="w-4 h-4" />
        </Button>
      </div>

      {/* Search and Filter */}
      <div className="border-b px-6 py-4 space-y-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder="Search templates..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>

        <div className="flex gap-2 flex-wrap">
          {CATEGORIES.map((category) => (
            <Button
              key={category.value}
              variant={selectedCategory === category.value ? 'default' : 'outline'}
              size="sm"
              onClick={() => setSelectedCategory(category.value)}
            >
              {category.label}
            </Button>
          ))}
        </div>
      </div>

      {/* Templates Grid */}
      <div className="flex-1 overflow-y-auto p-6">
        {filteredTemplates.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-muted-foreground">No templates found</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filteredTemplates.map((template) => (
              <Card
                key={template.id}
                className="cursor-pointer hover:shadow-md transition-shadow"
                onClick={() => setSelectedTemplate(template)}
              >
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <CardTitle className="text-base">{template.name}</CardTitle>
                      <CardDescription className="text-xs mt-1">
                        {template.description}
                      </CardDescription>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 mt-2">
                    <div className="flex items-center text-xs text-muted-foreground">
                      <Star className="w-3 h-3 mr-1 fill-yellow-400 text-yellow-400" />
                      {template.rating}
                    </div>
                    <div className="flex items-center text-xs text-muted-foreground">
                      <Download className="w-3 h-3 mr-1" />
                      {template.downloads}
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="flex flex-wrap gap-1">
                    {template.tags.map((tag) => (
                      <Badge key={tag} variant="secondary" className="text-xs">
                        {tag}
                      </Badge>
                    ))}
                  </div>
                  <Button
                    size="sm"
                    className="w-full mt-4"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleApply(template);
                    }}
                  >
                    Apply Template
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Template Detail Modal */}
      {selectedTemplate && (
        <div
          className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]"
          onClick={() => setSelectedTemplate(null)}
        >
          <Card className="w-full max-w-2xl max-h-[80vh] overflow-y-auto m-4" onClick={(e) => e.stopPropagation()}>
            <CardHeader>
              <div className="flex items-start justify-between">
                <div>
                  <CardTitle>{selectedTemplate.name}</CardTitle>
                  <CardDescription className="mt-2">{selectedTemplate.description}</CardDescription>
                </div>
                <Button variant="ghost" size="icon" onClick={() => setSelectedTemplate(null)}>
                  <X className="w-4 h-4" />
                </Button>
              </div>
              <div className="flex items-center gap-4 mt-4">
                <div className="flex items-center text-sm">
                  <Star className="w-4 h-4 mr-1 fill-yellow-400 text-yellow-400" />
                  {selectedTemplate.rating} rating
                </div>
                <div className="flex items-center text-sm text-muted-foreground">
                  <Download className="w-4 h-4 mr-1" />
                  {selectedTemplate.downloads} downloads
                </div>
                <Badge>{selectedTemplate.category}</Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <h4 className="font-semibold text-sm mb-2">System Prompt</h4>
                <div className="p-3 bg-muted rounded text-sm">
                  {selectedTemplate.prompt}
                </div>
              </div>

              <div>
                <h4 className="font-semibold text-sm mb-2">Configuration</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">Model:</span>
                    <Badge variant="outline">{selectedTemplate.model}</Badge>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-muted-foreground">Tools:</span>
                    <div className="flex flex-wrap gap-1">
                      {selectedTemplate.tools?.map((tool) => (
                        <Badge key={tool} variant="secondary" className="text-xs">
                          {tool}
                        </Badge>
                      ))}
                    </div>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-muted-foreground">Tags:</span>
                    <div className="flex flex-wrap gap-1">
                      {selectedTemplate.tags.map((tag) => (
                        <Badge key={tag} variant="outline" className="text-xs">
                          {tag}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </div>
              </div>

              <Button className="w-full" onClick={() => handleApply(selectedTemplate)}>
                Apply This Template
              </Button>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}

